package com.gonsin.project.creator.create;

import com.gonsin.project.creator.utils.CmdUtils;
import com.gonsin.project.creator.utils.JsUtils;
import org.apache.commons.io.FileUtils;

import javax.script.ScriptException;
import java.io.File;
import java.io.IOException;

public class CreateCmd {

    /**
     * 创建模板
     */
    private String template;

    public CreateCmd(String template) {
        this.template = template;
    }


    /**
     * 创建脚本
     */
    public void run(String[] args) throws IOException, ScriptException {
        String jarPath = args[0].trim();
        File templatePath = new File(jarPath + File.separator + "templates" + File.separator + template);
        if(!templatePath.exists()){
            throw new TemplateException("没有找到" + template + "模板目录");
        }
        File inputJs = new File(templatePath.getAbsolutePath() + File.separator + "input.js");
        if(!inputJs.exists()){
            throw new TemplateException("在模板" + template + "中，没有找到input.js文件");
        }

        boolean ignorePackageName = CmdUtils.contain(args, "--ignorePackageName");
        boolean force = CmdUtils.contain(args, "--force");

        String js = FileUtils.readFileToString(inputJs);
        IJavaScriptBinder binder = new JavaScriptBinder(templatePath, ignorePackageName, force);
        JsUtils.runJs(js, binder);
    }

}
